package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.Constants;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.WeidianTokenInfo;
import com.letv.whatslive.model.convert.WeidianTokenInfoConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.letv.whatslive.redis.JedisDAO;
import com.mongodb.*;
import com.mongodb.util.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 微店与乐嗨对应表
 * Created by 刘本龙 on 16-9-13.
 */
@Repository
public class WeiDianTokenInfoDAO extends BaseDAO {

    private final static Logger logger = LoggerFactory.getLogger(WeiDianTokenInfoDAO.class);

    protected String collectionName = "weidianTokenInfo";

    @Autowired
    protected JedisDAO jedisDAO;

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    public long insertWeidianTokenInfo(WeidianTokenInfo weidianTokenInfo) {
        DBObject obj = WeidianTokenInfoConvert.castWeidianTokenInfoToDBObject(weidianTokenInfo);
        return this.insert(obj);
    }

    public DBObject findAndModify(DBObject query , WeidianTokenInfo weidianTokenInfo) {
        DBObject obj = WeidianTokenInfoConvert.castWeidianTokenInfoToDBObject(weidianTokenInfo);
        return this.dbCollection.findAndModify(query, obj);
    }

    public List<WeidianTokenInfo> getAllWeidianTokenInfo(Integer start, Integer limit, Map<String, Object> params) {
        DBObject order = new BasicDBObject();
        order.put("createTime", -1);
        List<DBObject> weidianTokenInfoList = selectAll(start, limit, params, order);
        List<WeidianTokenInfo> result = Lists.newArrayList();
        for (DBObject obj : weidianTokenInfoList) {
            WeidianTokenInfo weidianTokenInfo = WeidianTokenInfoConvert.castDBObjectToWeidianTokenInfo(obj);
            result.add(weidianTokenInfo);
        }
        return result;
    }

    public WeidianTokenInfo getWeidianTokenInfoByOpenId(String openId){
        BasicDBObject query = new BasicDBObject();
        query.put("openid", openId);
        DBObject result = dbCollection.findOne(query);
        if (result == null) {
            return null;
        }else{
            WeidianTokenInfo weidianTokenInfo = WeidianTokenInfoConvert.castDBObjectToWeidianTokenInfo(result);
            return weidianTokenInfo;
        }
    }

    public List<WeidianTokenInfo> getWeidianTokenInfoListByParams(Integer start, Integer limit, Map<String, Object> params) {
        List<WeidianTokenInfo> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBObject order = new BasicDBObject();
            order.put("createTime", -1);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip)
                    .sort(order).limit(limit);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                WeidianTokenInfo weidianTokenInfo = WeidianTokenInfoConvert.castDBObjectToWeidianTokenInfo(dbObject);
                weidianTokenInfo.setUrl(Constants.WEIDIAN_SHOP_URL+weidianTokenInfo.getOpenid());
                result.add(weidianTokenInfo);
            }
        } catch (Exception e) {
            logger.error("getWeidianTokenInfoListByParams error!", e);
        }
        return result;
    }

    /**
     * 查询微店token的记录数
     * @param params 查询条件参数
     * @return 满足条件的文档记录数
     */
    public Long countWeidianTokenInfoByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }


    public List<WeidianTokenInfo> getAllWeidianTokenInfoByParams(Map<String, Object> params){
        List<WeidianTokenInfo> result = Lists.newArrayList();
        try {
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                WeidianTokenInfo weidianTokenInfo = WeidianTokenInfoConvert.castDBObjectToWeidianTokenInfo(dbObject);
                result.add(weidianTokenInfo);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 查询需要刷新token的数据
     * @param pageSize 查询条数
     * @param pageNo 第几页
     * @param time  限制时间
     * @return
     */
    public List<WeidianTokenInfo> queryRefreshTokenDatas(int pageSize, int pageNo, long time){
        List<WeidianTokenInfo> result = Lists.newArrayList();
        try {
            /**
             {"$project":{
             "cha":{
             "$subtract":[
             {
             "$add":[
             {"$multiply":["$expire_in",1000]},
             "$updateTime"
             ]
             },
             222222
             ]
             },
             "access_token":1,
             "refresh_token":1,
             "openid":1,
             "dinggou":1,
             "status":1,
             "_id":1
             }}
             */
            List<DBObject> list = new ArrayList<DBObject>();
            DBObject query = (DBObject) JSON.parse(
                    "{\"$project\":{" +
                    "   \"cha\":{" +
                    "       \"$subtract\":[" +
                    "           {" +
                    "               \"$add\":[" +
                    "                   {\"$multiply\":[\"$expire_in\",1000]}," +
                    "                   \"$updateTime\"" +
                    "               ]" +
                    "           }," +
                    "           " + System.currentTimeMillis() +
                    "       ]\n" +
                    "   },\n" +
                    "   \"access_token\":1," +
                    "   \"refresh_token\":1,"+
                    "   \"openid\":1," +
                    "   \"dinggou\":1," +
                    "   \"status\":1," +
                    "   \"_id\":1" +
                    "}}");
            list.add(query);
            list.add(new BasicDBObject("$match", new BasicDBObject("cha", new BasicDBObject("$lt", time))));//相当于查询过滤
            list.add(new BasicDBObject("$skip", pageSize * pageNo));//效率可能会慢，不过现在数据量很小，后续优化！！！！！！！
            list.add(new BasicDBObject("$limit", pageSize));

            AggregationOutput aggregate = this.dbCollection.aggregate(list);
            Iterator<DBObject> iterator = aggregate.results().iterator();
            while (iterator.hasNext()) {
                DBObject dbObject = iterator.next();
                WeidianTokenInfo weidianTokenInfo = WeidianTokenInfoConvert.castDBObjectToWeidianTokenInfo(dbObject);
                result.add(weidianTokenInfo);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 根据查询参数Map获取查询条件对象
     * @param params 查询参数Map
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {

            if (params.get("access_token") != null) {
                query.put("access_token", ObjectUtils.toString(params.get("access_token")));
            }

            //这里只查询小于，如果有其他需求，在单独写函数
            if (params.get("expire_in") != null) {
                query.put("expire_in", new BasicDBObject("$lt", ObjectUtils.toInteger(params.get("expire_in"))));
            }

            if (params.get("refresh_token") != null) {
                query.put("refresh_token", ObjectUtils.toString(params.get("refresh_token")));
            }
            if (params.get("openid") != null) {
                query.put("openid", ObjectUtils.toString(params.get("openid")));
            }
            if (params.get("shop_name") != null) {
                query.put("shop_name", ObjectUtils.toString(params.get("shop_name")));
            }
            if (params.get("shop_name_regex") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("shop_name_regex") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("shop_name", pattern);
            }
            if (params.get("scope") != null) {
                query.put("scope", ObjectUtils.toInteger(params.get("scope")));
            }
            if (params.get("shop_logo") != null) {
                query.put("shop_logo", ObjectUtils.toString(params.get("shop_logo")));
            }
            if (params.get("status") != null) {
                query.put("status", ObjectUtils.toInteger(params.get("status")));
            }

//            if(params.get("startTime_start") != null && params.get("startTime_end") != null){
//                query.put("createTime", new BasicDBObject("$gt",
//                        ObjectUtils.toLong(params.get("startTime_start"))).append("$lte", ObjectUtils.toLong(params.get("startTime_end"))));
//
//            }
        }
        return query;
    }

    /**
     * 更新直播信息
     *
     * @param weidianTokenInfo
     */
    public boolean updateWeidianTokenInfo(WeidianTokenInfo weidianTokenInfo) {

        DBObject queryCondition = new BasicDBObject();
        Long pid = weidianTokenInfo.getId();
        queryCondition.put("_id", pid); // 用来确定要修改的文档
        BasicDBObject setValue = (BasicDBObject) WeidianTokenInfoConvert.castWeidianTokenInfoToDBObject(weidianTokenInfo);
        //剔除主键修改
        if (setValue.containsField("_id")) {
            setValue.removeField("_id");
        }
        DBObject updateValue = new BasicDBObject("$set", setValue);
        WriteResult update = this.dbCollection.update(queryCondition, updateValue, true, false);
        return update.isUpdateOfExisting();
    }

}
